package com.hjb.uils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author JianBinHuang
 * @Description
 * @Date 2021/8/31 14:42
 */
public class MybatisUtils {

    private static SqlSessionFactory factory;

    /**
     *     //让每个线程都有一个sqlSession,这样就不会互相干扰
     */
    private static final ThreadLocal<SqlSession> THREAD_LOCAL=new ThreadLocal<>();


    /**
     * 创建一个工厂对象
     */
    static{
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory=new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * openSqlSession
     * @return
     */
    public static SqlSession openSession(){
        SqlSession sqlSession = THREAD_LOCAL.get();
        if(sqlSession==null){
            sqlSession = factory.openSession();
            THREAD_LOCAL.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 关闭事务
     */
    public static void closeSqlSession(){

        SqlSession sqlSession = THREAD_LOCAL.get();
        sqlSession.close();
        THREAD_LOCAL.remove();
    }

    /**
     *     //提交事务
     */
    public static void commitSession(){
        SqlSession sqlSession = openSession();
        sqlSession.commit();
        closeSqlSession();
    }

    /**
     * 回滚事务
     */
    public static void rollback(){
        SqlSession sqlSession = openSession();
        sqlSession.rollback();
        closeSqlSession();
    }


    /**
     * 处理映射接口
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T extends Object> T getMapper(Class<T> clazz){

        SqlSession sqlSession = openSession();

        return sqlSession.getMapper(clazz);

    }

}